package com.example.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

public class ZipUtil {
    private static byte[] buffer = new byte[1024];

    private static final String ENCODE_UTF_8 = "UTF-8";

    /**
     * 压缩文件或路径
     *
     * @param zip      压缩的目的地址 例如：D://zipTest.zip
     * @param srcFiles 压缩的源文件
     */
    public static void zipFile(String zip, List<File> srcFiles) {
        try {
            // 判断是否为压缩后的文件后缀是否为.zip结尾
            if (zip.endsWith(".zip") || zip.endsWith(".ZIP")) {
                ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(new File(zip)));
                // 设置编码
                zipStream.setEncoding(ENCODE_UTF_8);
                for (File file : srcFiles) {
                    zipFile(zip, zipStream, file, "");
                }
                zipStream.close();
            } else {
                System.out.println("target file[" + zip + "] is not .zip type file");
            }
        } catch (IOException ignored) {
        }
    }

    /**
     * @param zip     压缩的目的地址 例如：D://zipTest.zip
     * @param zipOut
     * @param srcFile 被压缩的文件
     * @param path    在zip中的相对路径
     * @throws IOException
     */
    private static void zipFile(String zip, ZipOutputStream zipOut, File srcFile, String path) throws IOException {
        System.out.println(" 开始压缩文件[" + srcFile.getName() + "]");

        // 路径拼接处理
        if (!"".equals(path) && !path.endsWith(File.separator)) {
            path += File.separator;
        }

        // 测试此抽象路径名定义的文件或目录是否存在
        if (!srcFile.exists()) {
            System.out.println("压缩失败，文件或目录 " + srcFile + " 不存在!");
        } else {
            if (!srcFile.getPath().equals(zip)) {
                if (srcFile.isDirectory()) {
                    // listFiles能够获取当前文件夹下的所有文件和文件夹，如果文件夹A下还有文件D，那么D也在childs里。
                    File[] fileArray = srcFile.listFiles();
                    if (fileArray.length == 0) {
                        zipOut.putNextEntry(new ZipEntry(path + srcFile.getName() + File.separator));
                        zipOut.closeEntry();
                    } else {
                        for (File file : fileArray) {
                            zipFile(zip, zipOut, file, path + srcFile.getName());
                        }
                    }
                } else {
                    FileInputStream _in = new FileInputStream(srcFile);
                    zipOut.putNextEntry(new ZipEntry(path + srcFile.getName()));
                    int len = 0;
                    while ((len = _in.read(buffer)) > 0) {
                        zipOut.write(buffer, 0, len);
                    }
                    _in.close();
                    zipOut.closeEntry();
                }
            }
        }
    }

    /**
     * 解压缩ZIP文件，将ZIP文件里的内容解压到targetDIR目录下
     *
     * @param zipName           待解压缩的ZIP文件名
     * @param descDir           目标目录
     */
    public static List<File> upzipFile(String zipName, String descDir) {
        return upzipFile(new File(zipName), descDir);
    }

    /**
     * 对.zip文件进行解压缩
     *
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static List<File> upzipFile(File zipFile, String descDir) {
        List<File> fileList = new ArrayList<File>();
        try {
            if (!zipFile.exists()) {
                System.out.println("解压失败，文件 " + zipFile + " 不存在!");
                return fileList;
            }
            ZipFile distZipFile = new ZipFile(zipFile, ENCODE_UTF_8);
            for (Enumeration entries = distZipFile.getEntries(); entries.hasMoreElements(); ) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                File file = new File(descDir + File.separator + entry.getName());
                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    File parent = file.getParentFile();
                    if (!parent.exists()) {
                        parent.mkdirs();
                    }
                    InputStream inPutstram = distZipFile.getInputStream(entry);
                    OutputStream outPutStream = new FileOutputStream(file);
                    int len = 0;
                    while ((len = inPutstram.read(buffer)) > 0) {
                        outPutStream.write(buffer, 0, len);
                    }
                    inPutstram.close();
                    outPutStream.flush();
                    outPutStream.close();  
                    fileList.add(file);
                }
            }
            distZipFile.close();
        } catch (IOException e) {
        }
        return fileList;
    }

    /**
     * 对临时生成的文件夹和文件夹下的文件进行删除
     */
    public static void deletefile(String delpath) {
        try {
            File file = new File(delpath);
            // 判断是不是一个目录
            if (!file.isDirectory()) {
                file.delete();
            } else if (file.isDirectory()) {
                String[] filelist = file.list();
                for (String aFilelist : filelist) {
                    File delfile = new File(delpath + File.separator + aFilelist);
                    if (!delfile.isDirectory()) {
                        delfile.delete();
                    } else if (delfile.isDirectory()) {
                        deletefile(delpath + File.separator + aFilelist);// 递归删除
                    }
                }
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
//    	File file = new File("e://member4");
//    	File[] listFiles = file.listFiles();
//    	List<String> personNameList = new ArrayList<>();
//    	for(File file2:listFiles) {
//    		String name = file2.getName();
//    		String[] nameArray = name.split("-");
//    		String personName = nameArray[0];
//    		if(!personNameList.contains(personName)) {
//    			personNameList.add(personName);
//    			StringBuilder sb = new StringBuilder(personName);
//    			sb.append("-").append("男").append("-").append("18652636548").append("-").append("0").append(".jpg");
//    			String  newName = sb.toString();
//    			FileUtils.copyFile(file2, new File("e://member5//"+newName));
//    		}
//    		
//    	}
    	
    	List<String> cities = Arrays.asList("Milan", 
                "London", 
                "New York", 
                "San Francisco");
String citiesCommaSeparated = String.join(",", cities);
System.out.println(citiesCommaSeparated);
    	
    }
    
   /* @GetMapping("/fetch/imags")
    public void fetchImages() throws Exception {
        File file = new File("e://yf.json");
        String json = FileUtils.readFileToString(file);
        List<MemberTempInfo> memberTempInfos = JSON.parseArray(json, MemberTempInfo.class);
        for (MemberTempInfo memberTempInfo : memberTempInfos) {
            String name = memberTempInfo.getName();
            List<String> urls = memberTempInfo.getUrls();

            File memberFile = new File("e://member2//", name);
            if (!memberFile.exists()) {
                memberFile.mkdirs();
            }
            for (String url : urls) {
                URL urs1 = new URL(url);
                HttpURLConnection conn = null;
                try {
                    conn = (HttpURLConnection) urs1.openConnection();

                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5 * 1000);
                    InputStream inStream = conn.getInputStream();
                    byte[] data = readInputStream(inStream);
                    File personImg = new File(memberFile, name + "-" + (System.currentTimeMillis()) + ".jpg");
                    FileOutputStream outStream = new FileOutputStream(personImg);
                    outStream.write(data);
                    outStream.close();
                } catch (IOException e) {
                    System.out.println(e);
                }

            }

        }
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }*/
}